package com.qi.utils;

import cn.hutool.core.lang.UUID;
import com.qi.config.ImageConfigReader;
import com.qi.exception.ServerException;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.IOUtils;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class ImageUtil {

    public static String upload(MultipartFile file) {
        // 编译后的类路径
        String ab = null;
        try {
            ab = ResourceUtils.getURL("classpath:").getPath();
        } catch (FileNotFoundException e) {
            throw new ServerException(e.getMessage());
        }
        // 构造文件名
        String fileName = UUID.fastUUID().toString().replaceAll("-", "") + "." + file.getContentType().substring(file.getContentType().indexOf("/") + 1);
        // 文件路径（简路径）
        String filePath = ImageConfigReader.getLocation() + fileName;
        File f = new File(ab, filePath);
        if (!f.exists()) {
            f.mkdirs();
        }
        try {
            file.transferTo(f);
        } catch (IOException e) {
            throw new ServerException(e.getMessage());
        }
        return fileName;
    }

    public static String getImageBase64(String imageLocation) {
        String s = null;
        try {
            File f = ResourceUtils.getFile(ResourceUtils.getURL("classpath:" + ImageConfigReader.getLocation()).getPath() + imageLocation);
            FileInputStream fis = new FileInputStream(f);
            byte[] byteArray = IOUtils.toByteArray(fis);
            s = Base64.encodeBase64String(byteArray);
            fis.close();
        } catch (IOException e) {
            throw new ServerException(e.getMessage());
        }
        return s;
    }
}
